package com.apps.controller;

import com.apps.config.QqConnectConfig;
import com.apps.config.WebSiteConfig;
import com.apps.helper.PageConextHelper;
import com.apps.helper.UserConextHelper;
import com.apps.member.service.IKupaMemberService;
import com.apps.module.thirdparty.tencent.model.vo.WechatAccessToken;
import com.apps.module.thirdparty.tencent.model.vo.WechatUserInfo;
import com.apps.module.thirdparty.tencent.service.IKupaWechatService;
import com.apps.sexctption.NullException;
import com.apps.sutils.StringUtils;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.oauth.Oauth;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

/**
 * qq登录
 */
@Slf4j
@Controller
@RequestMapping(value = "/thirdparty")
public class LoginConnectController
{

    @Autowired
    private WebSiteConfig webSiteConfig;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private IKupaWechatService wechatService;

    @Autowired
    private QqConnectConfig qqConnectConfig;

    @Autowired
    private IKupaMemberService memberService;

    /**
     * 登录页面
     * @param modelAndView
     * @param request
     * @return
     */
    @RequestMapping("/login.html")
    public ModelAndView Login(ModelAndView modelAndView,
                              HttpServletRequest request)
    {
        modelAndView.setViewName("home/login");
        return modelAndView;
    }

    /**
     * 退出登录
     * @param request
     * @param httpResponse
     */
    @RequestMapping("/loginout.html")
    public void LoginOut(HttpServletRequest request,
                         HttpServletResponse httpResponse) throws Exception
    {
        UserConextHelper.cleanCurrentMember();
        memberService.loginOut(UserConextHelper.getCurrentMember().getId());
        //回到历史页面
        httpResponse.sendRedirect("/thirdparty/qq/to_qq_login.html");
    }
    /**
     * qq登录授权页面
     * @param request
     * @param response
     */
    @SneakyThrows
    @RequestMapping(value = "/qq/to_qq_login.html")
    public void ToQqLogin(HttpServletRequest request,
                          HttpServletResponse response)
    {
        response.setContentType("text/html;charset=utf-8");
        response.sendRedirect(new Oauth().getAuthorizeURL(request));
    }

    /**
     * qq登录回调
     * @param code
     * @param state
     */
    @SneakyThrows
    @RequestMapping(value = "/qq/qqLoginCallback")
    public void qqLoginCallback(@RequestParam(value = "code") String code,
                                @RequestParam(value = "state") String state,
                                HttpServletRequest request,
                                HttpServletResponse response)
    {
        AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);
        if(null == accessTokenObj || StringUtils.isEmpty(accessTokenObj.getAccessToken()))
            throw new NullException("获取accesstoken失败");
        // 利用获取到的accessToken 去获取当前用的openid
        OpenID openIDObj = new OpenID(accessTokenObj.getAccessToken());
        if(null == openIDObj || StringUtils.isEmpty(openIDObj.getUserOpenID()))
            throw new NullException("获取openid失败");
        // 去获取用户在Qzone的昵称等信息
        UserInfo qzoneUserInfo = new UserInfo(accessTokenObj.getAccessToken(), openIDObj.getUserOpenID());
        //执行qq登录
        memberService.qqLogin(openIDObj.getUserOpenID(),
                              qzoneUserInfo.getUserInfo().getNickname(),
                              qzoneUserInfo.getUserInfo().getAvatar().getAvatarURL100(),
                              qzoneUserInfo.getUserInfo().getGender().equals("男")?0:1);
        response.sendRedirect(PageConextHelper.getHistoryPage());
    }

    /**
     * 微信登录
     * @param request
     * @param response
     */
    @SneakyThrows
    @RequestMapping(value = "/wechat/to_wechat_login.html")
    public void ToWechatLogin(HttpServletRequest request,
                              HttpServletResponse response)
    {
        response.setContentType("text/html;charset=utf-8");
        response.sendRedirect("https://open.weixin.qq.com/connect/qrconnect?appid="+webSiteConfig.getWx_Pc_AppID()+"&redirect_uri="+ URLEncoder.encode(webSiteConfig.getWx_Pc_Redirect_Uri())+"&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect");
    }

    /**
     * 微信登录回调
     * @param code
     * @param state
     * @param response
     */
    @SneakyThrows
    @RequestMapping(value = "/wechat/wechatLoginCallback")
    public void wechatLoginCallback(@RequestParam(value = "code") String code,
                                    @RequestParam(value = "state") String state,
                                    HttpServletResponse response)
    {
        WechatAccessToken wechatAccessToken =wechatService.getAccess(code);
        WechatUserInfo userInfo=wechatService.getUserInfo(wechatAccessToken);
        memberService.wxLogin(userInfo.getOpenid(),userInfo.getNickname(),userInfo.getHeadimgurl(),userInfo.getSex());
        //跳回上一页
        response.sendRedirect(PageConextHelper.getHistoryPage());
    }


}
